const int rows = 4;
const int cols = 4;
const int debounceTime = 20;
const char keymap[rows][cols] = {
  {
    '1', '2', '3', 'A'
  },
  {
    '4', '5', '6', 'B'
  },
  {
    '7', '8', '9', 'C'
  },
  {
    '*', '0', '#', 'D'
  }
};

const int rowPins[rows] = {4,5,6,7};
const int colPins[cols] = {8,9,10,11};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  for (int row = 0; row < rows; row++) {
    pinMode(rowPins[row], INPUT);
    digitalWrite(rowPins[row], HIGH);

  }
  for (int col = 0; col < cols; col++) {
    pinMode(colPins[col], OUTPUT);
    digitalWrite(colPins[col], HIGH);

  }
}

void loop() {
  // put your main code here, to run repeatedly:
  char key = getKey();
  if (key != 0) {
    Serial.println(key);
  }
}

char getKey() {
  char key = 0;
  for (int col = 0; col < cols; col++) {
    digitalWrite(colPins[col], LOW);
    for (int row = 0; row < rows; row++) {
      if (digitalRead(rowPins[row]) == LOW) {
        delay(debounceTime);
        while (digitalRead(rowPins[row]) == LOW) {
          ;
        }
        key = keymap[row][col];
      }
    }
    digitalWrite(colPins[col], HIGH);

  }
  return key;
}
